package com.pai4j.zwiki.service.queue;

import com.pai4j.common.util.JsonUtil;
import com.pai4j.zwiki.dto.ZWikiTaskMessage;
import com.pai4j.zwiki.enums.ZWikiTaskType;
import com.pai4j.zwiki.service.ZWikiTaskQueueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Service;

/**
 * ZWiki任务消息消费者
 * 负责消费任务队列中的消息并执行相应处理
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
@RocketMQMessageListener(
        topic = "zwiki_task_queue",
        consumerGroup = "zwiki_task_consumer_group"
)
public class ZWikiTaskConsumer implements RocketMQListener<String> {

    private final ZWikiTaskQueueService taskQueueService;

    @Override
    public void onMessage(String message) {
        log.info("接收到ZWiki任务消息: {}", message);

        try {
            // 解析任务消息
            ZWikiTaskMessage taskMessage = JsonUtil.fromJson(message, ZWikiTaskMessage.class);

            if (taskMessage == null || taskMessage.getTaskId() == null) {
                log.error("任务消息解析失败或taskId为空: {}", message);
                return;
            }

            log.info("开始处理ZWiki任务: taskId={}, taskType={}", 
                    taskMessage.getTaskId(), taskMessage.getTaskType());

            // 根据任务类型分发处理
            ZWikiTaskType taskType = ZWikiTaskType.fromCode(taskMessage.getTaskType());
            
            if (taskType == null) {
                log.error("未知的任务类型: {}", taskMessage.getTaskType());
                taskQueueService.markTaskFailed(taskMessage.getTaskId(), "未知的任务类型");
                return;
            }

            // 执行任务处理
            switch (taskType) {
                case PROJECT_ANALYSIS:
                    taskQueueService.executeProjectAnalysisTask(taskMessage.getTaskId());
                    break;
                case THESIS_GENERATION:
                    taskQueueService.executeThesisGenerationTask(taskMessage.getTaskId());
                    break;
                case THESIS_OPTIMIZATION:
                    taskQueueService.executeThesisOptimizationTask(taskMessage.getTaskId());
                    break;
                default:
                    log.warn("未处理的任务类型: {}", taskType);
                    break;
            }

            log.info("ZWiki任务处理完成: taskId={}", taskMessage.getTaskId());

        } catch (Exception e) {
            log.error("处理ZWiki任务消息失败: message={}, error={}", message, e.getMessage(), e);
            // 消费者失败会触发重试机制
            throw new RuntimeException("处理任务失败", e);
        }
    }
}

